package code.extract;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

/**
 * @author Fang Lu, fanglupku@gmail.com
 */

public class CodeJudge {
	// public static boolean isCode(String originString){
	// if (originString == null || originString.trim().length() < 10){
	// return false;
	// }
	// if (originString.indexOf(';') == -1){
	// return false;
	// }
	// if (originString.indexOf('(') == -1){
	// return false;
	// }
	// return true;
	// }

	public static boolean isCode(String content) {
		BufferedReader br = new BufferedReader(new StringReader(content));
		String line = null;
		int totalLOC = 0, isCodeLOC = 0;
		boolean MUST_OCCUR = false;
		try {
			while ((line = br.readLine()) != null) {
				// only handle non-blank lines
				if (line.trim().length() > 0){
					if( (!MUST_OCCUR) && hasMustOccurSymbol(line)){
						MUST_OCCUR = true;
					}
					if (isCodeLine(line.trim())) {
						isCodeLOC++;
					}
					totalLOC++;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		System.out.println(totalLOC + "/" + isCodeLOC + "/" + MUST_OCCUR + "/" + ((double)isCodeLOC / ((double) totalLOC)) );
		if (totalLOC >0&&MUST_OCCUR) {
			if ((double)isCodeLOC / ((double) totalLOC) > 0.2) {
//				System.out.println("CODE------------------");
//				System.out.println(content);
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}

	}

	public final static String[] codeEndSymbol = { "{", "}", ";", "=" };
	public final static String[] codeKeywordSymbol = { "public", "private",
			"protected", "return", "package", "import" };
	public final static String[] mustOccurSymbol = {"(",")"};
	
	public static boolean hasMustOccurSymbol(String line){
		for(String s:mustOccurSymbol)
			if(line.contains(s))	
				return true;
		return false;
	}
	
	public static boolean isCodeLine(String line) {
		for (String s : codeEndSymbol) {
			if (line.endsWith(s)) {
				return true;
			}
		}
		for (String s : codeKeywordSymbol) {
			if (line.startsWith(s)) {
				return true;
			}
		}
		return false;
	}
}
